<template>
  <XcForm
    ref="formView"
    :key="tableConfig.length"
    v-model:visible="visible"
    :state="state"
    :closeReset="true"
    :title="title"
    :config="tableConfig"
    :values="formData"
    isDialog
    :colProps="12"
    :dialogWidth="hasParams ? 900 : 500"
    :dialogHeight="hasParams ? 500 : 200"
    dialogMaximize
    @open="init"
    @close="close"
    @submit="submit">
    <template #params>
      <NodeTree v-loading="isLoading" class="node-tree" :data="params" />
    </template>
  </XcForm>
</template>

<script lang="ts" setup>
import type { ColumnItem, XcFormInstance } from "@xc-components/xc-form/types";
import { ElMessage } from "element-plus";
import { computed, ref, nextTick, type Ref } from "vue";
import type { TreeItem, ConfigParams } from "../../../../api/adjust/index.d";
const authStore = {
  calibrationName: "开场校准管理器"
};
const emits = defineEmits(["update"]);
const visible = defineModel<boolean>();
const props = withDefaults(defineProps<{ detail: Partial<TreeItem>; apiConfig: ConfigParams; currentKey: string }>(), {
  detail: () => ({}),
  apiConfig: () => ({}) as ConfigParams,
  currentKey: ""
});
const title = computed(() => {
  const { children, pName, name } = props.detail;
  return children ? "新增" + name : "修改" + pName;
});
const isAdd = computed(() => !!props.detail.children);
const hasParams = computed(() => ["lineinfo", "positioninfo"].includes(props.currentKey)); // 是否有参数配置
const tableConfig = ref<ColumnItem<TreeItem>[]>([]);
const state = ref<"loading" | "error" | "">("");
const formData = ref({}) as Ref<TreeItem>;
const formView: Ref<XcFormInstance<TreeItem> | null> = ref(null);
const params = ref([]);
const isLoading = ref(false);

/**
 * @description: 初始化
 * @return {*}
 */
const init = () => {
  let config: ColumnItem<TreeItem>[] = [
    { label: "名称", prop: "name", required: true },
    { label: "参数", prop: "params", type: "slot", slot: "params" }
  ];
  if (["freqscope", "antennafactor"].includes(props.currentKey)) {
    config = config.slice(0, 1);
  }
  tableConfig.value = config;
  nextTick(() => {
    if (isAdd.value) {
      getAddParams();
    } else {
      params.value = JSON.parse(JSON.stringify(props.detail.params || []));
      getInfo();
    }
  });
};
/**
 * @description: 获取新增校准的参数
 * @param {*} row
 * @return {*}
 */
const getAddParams = async () => {
  const { getParams } = props.apiConfig;
  if (getParams) {
    isLoading.value = true;
    const apiParams = {} as { calibrationType?: string };
    if (props.currentKey === "lineinfo") {
      apiParams.calibrationType = props.detail.id;
    }
    const { data } = await getParams(apiParams, { calibrationName: authStore.calibrationName });
    params.value = data || [];
    isLoading.value = false;
  }
};
/**
 * @description: 详情
 * @param {*} isLoading
 * @return {*}
 */
const getInfo = async () => {
  formData.value = {} as TreeItem;
  Object.entries(props.detail || {}).forEach(([key, value]) => {
    if (key !== "params") {
      formData.value[key as keyof TreeItem] = value as never;
    }
  });
};

/**
 * @description: 保存
 * @param {*} value
 * @param {*} done
 * @return {*}
 */
const submit = async ({ value, done }: { value: any; done: (isClose?: boolean) => void }) => {
  try {
    const { id, pId, calibrationType } = props.detail;
    const { add, edit, addKey, editKey } = props.apiConfig;
    const api = isAdd.value ? add : edit;
    await api!!(
      {
        [isAdd.value ? addKey : editKey || addKey]: {
          name: value.name,
          calibrationType: calibrationType || (pId === "lineinfo" ? id : undefined),
          id: isAdd.value ? "" : id,
          params: hasParams.value ? params.value : undefined
        }
      },
      { calibrationName: authStore.calibrationName }
    );
    done?.();
    visible.value = false;
    ElMessage({ type: "success", message: isAdd.value ? "新增成功" : "修改成功" });
    emits("update");
  } catch {
    done?.();
  }
};
const close = () => {
  formData.value = {} as TreeItem;
};
</script>
<style lang="scss" scoped></style>
